package com.zero.flutter_gromore_ads.page;

import android.content.Context;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTDrawFeedAd;
import com.bytedance.sdk.openadsdk.TTFeedAd;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationExpressRenderListener;
import com.zero.flutter_gromore_ads.PluginDelegate;
import com.zero.flutter_gromore_ads.event.AdEventAction;
import com.zero.flutter_gromore_ads.load.FeedAdManager;
import com.zero.flutter_gromore_ads.utils.UIUtils;

import java.util.HashMap;
import java.util.Map;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.platform.PlatformView;

/**
 * Draw 信息流广告 View
 */
class AdDrawFeedView extends BaseAdPage implements PlatformView, MediationExpressRenderListener {
    private final String TAG = AdDrawFeedView.class.getSimpleName();
    @NonNull
    private final FrameLayout frameLayout;
    private final PluginDelegate pluginDelegate;
    private int id;
    private TTDrawFeedAd fad;
    private View adView;
    private MethodChannel methodChannel;


    AdDrawFeedView(@NonNull Context context, int id, @Nullable Map<String, Object> creationParams, PluginDelegate pluginDelegate) {
        this.id = id;
        this.pluginDelegate = pluginDelegate;
        methodChannel = new MethodChannel(this.pluginDelegate.bind.getBinaryMessenger(), PluginDelegate.KEY_DRAW_FEED_VIEW + "/" + id);
        frameLayout = new FrameLayout(context);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        frameLayout.setLayoutParams(params);
        MethodCall call = new MethodCall("AdDrawFeedView", creationParams);
        showAd(this.pluginDelegate.activity, call);
    }

    @NonNull
    @Override
    public View getView() {
        return frameLayout;
    }

    @Override
    public void dispose() {
        removeAd();
    }

    @Override
    public void loadAd(@NonNull MethodCall call) {
        fad = FeedAdManager.getInstance().getDrawAd(Integer.parseInt(this.posId));
        if (fad != null) {
            fad.setExpressRenderListener(this);
            bindDislikeAction(fad);
            fad.render();
        }
    }

    /**
     * 移除广告
     */
    private void removeAd() {
        frameLayout.removeAllViews();
    }

    /**
     * 销毁广告
     */
    private void disposeAd() {
        removeAd();
        FeedAdManager.getInstance().removeDrawAd(Integer.parseInt(this.posId));
        if (fad != null) {
            fad.destroy();
        }
        // 关闭广告
        if (methodChannel != null) {
            methodChannel.invokeMethod("adClose", null);
        }
    }

    public void onAdClosed() {
        Log.i(TAG, "onAdClosed");
        // 添加广告事件
        sendEvent(AdEventAction.onAdClosed);
        disposeAd();
    }

    @Override
    public void onAdClick() {
        Log.i(TAG, "onAdClicked");
        // 添加广告事件
        sendEvent(AdEventAction.onAdClicked);
    }

    @Override
    public void onAdShow() {
        Log.i(TAG, "onAdShow");
        // 添加广告事件
        sendEvent(AdEventAction.onAdExposure);
        // 添加 Ecmp 事件
        if (fad != null) {
            sendEcmpEvent(fad.getMediationManager());
        }
    }

    @Override
    public void onRenderFail(View view, String s, int i) {
        Log.e(TAG, "onRenderFail code:" + i + " msg:" + s);
        // 添加广告错误事件
        sendErrorEvent(i, s);
        onAdClosed();
    }

    @Override
    public void onRenderSuccess(View view, float width, float height, boolean b) {
        Log.i(TAG, "onRenderSuccess width:" + width + " height:" + height);
        // 添加广告事件
        sendEvent(AdEventAction.onAdPresent);
        adView = fad.getAdView();
        if (adView != null && adView.getParent() != null) {
            ((ViewGroup) adView.getParent()).removeAllViews();
        }
        // 设置按钮的布局参数，使其在帧布局中居中
        FrameLayout.LayoutParams adParams = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.WRAP_CONTENT,
                FrameLayout.LayoutParams.WRAP_CONTENT
        );
        adParams.gravity = Gravity.CENTER;
        frameLayout.addView(adView,adParams);

        // 等待广告视图完成布局后获取实际尺寸
        adView.post(new Runnable() {
            @Override
            public void run() {
                float realWidth = UIUtils.px2dip(activity, adView.getWidth());
                float realHeight = UIUtils.px2dip(activity, adView.getHeight());
                
                // 将实际尺寸发送到 Flutter 端
                Map<String, Object> params = new HashMap<>();
                params.put("width", realWidth);
                params.put("height", realHeight);
                if (methodChannel != null) {
                    methodChannel.invokeMethod("adResize", params);
                }
            }
        });
    }

    /**
     * 接入dislike 逻辑，有助于提示广告精准投放度
     * 和后续广告关闭逻辑处理
     *
     * @param ad 广告 View
     */
    private void bindDislikeAction(TTFeedAd ad) {
        ad.setDislikeCallback(activity, new TTAdDislike.DislikeInteractionCallback() {
            @Override
            public void onSelected(int i, String s, boolean b) {
                onAdClosed();
            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onShow() {

            }
        });
    }
}